<?php

namespace app\api\service;

use app\api\model\AdminModel;
use app\api\model\CompanyModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class CompanyService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 添加、编辑保司信息
     */
    public function changeCompany($params)
    {
        $Validate = new Validate([
            'name' => 'require',
            'bankNo' => 'require',
            'bankName' => 'require',
            'bankTitle' => 'require',
            'insureEmail' => 'require',
            'insureEmailSpare' => 'require',
            'correctionEmail' => 'require',
            'correctionEmailSpare' => 'require',
            'isSpecial' => 'require',
            'premiumSetting' => 'require',
            'premiumRule' => 'require',
            'phone' => 'require',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }

        Db::startTrans();
        try{
            $saveData = [
                'name' => $params['name'],//'保司名称',
                'bank_no' => $params['bankNo'],//'保司银行账号',
                'bank_name' => $params['bankName'],//'开户行账号名称',
                'bank_title' => $params['bankTitle'],//'开户行',
                'insure_email' => $params['insureEmail'],//'投保邮箱',
                'insure_email_spare' => $params['insureEmailSpare'],//'投保备用邮箱',
                'correction_email' => $params['correctionEmail'],//'批改邮箱',
                'correction_email_spare' => $params['correctionEmailSpare'],//'批改备用邮箱',
                'is_special' => $params['isSpecial'],//'是否支持开专票  0  不支持  1 支持',
                'special_ticket' => isset($params['specialTicket']) ? $params['specialTicket'] : 0,//专票最低开具金额',
                'premium_setting' => $params['premiumSetting'],//'保费精确位数  2  精确两位     4  精确四位',
                'premium_rule' => $params['premiumRule'],//'保费计算规则： 1 四舍五入 2 进一 3 截取',
                'phone' => $params['phone'],
            ];

            if (!empty($params['id']))
            {
                $saveData['u_time'] = datetime(time(), 'Y-m-d H:i:s');
                $res = CompanyModel::getInstance()->update($params['id'], $saveData);
            }else{
                $saveData['admin_id'] = $this->uid;
                $saveData['c_time'] = datetime(time(), 'Y-m-d H:i:s');
                $res = CompanyModel::getInstance()->insert($saveData);
            }
            Db::commit();

            LogService::getInstance()->writeSysLog([
                'operation' => '/api/company/changeICompany',
                'title' => !empty($params['id']) ? '编辑' : '添加',
                'content' => $params,
            ]);

            $reData = [
                'type' => $res ? true : false,
                'msg' => $res
            ];
            return $reData;
        }catch (Exception $e)
        {
            Db::rollback();
            return [
                'type' => false,
                'msg' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取指定保司信息
     */
    public function getCompanyInfo($params)
    {
        $Validate = new Validate([
            'id' => 'require'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $res = CompanyModel::getInstance()->find($params['id'], 'id, name, bank_no AS bankNo, bank_name AS bankName, bank_title AS bankTitle, insure_email AS insureEmail, insure_email_spare AS insureEmailSpare, correction_email AS correctionEmail, correction_email_spare AS correctionEmailSpare, is_special AS isSpecial, special_ticket AS specialTicket, premium_setting AS premiumSetting, premium_rule AS premiumRule, phone');
        return $res;
    }

    /**
     * 获取保司信息 - 筛选用
     */
    public function getCompany($params)
    {
        $where = [];
        if (!empty($params['name']))
        {
            $where['name'] = ['LIKE', '%'.$params['name'].'%'];
        }
        $list = CompanyModel::getInstance()->select($where, 'id,name', 0, 100000);
        return $list;
    }

    /**
     * 获取保司列表
     */
    public function getCompanyList($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $where = [];

        if ($this->uid > 1)
        {
            $adminIds[] = $this->uid;
            $thisAdminIds = array_column(AdminService::getInstance()->getAdmin([], true), 'id');
            $adminIds = array_merge($adminIds, $thisAdminIds);
            $teamIds = AdminModel::getInstance()->value([
                'id' => ['eq', $this->uid]
            ], 'team');
            $teamAdminIds = AdminModel::getInstance()->column([
                'team' => ['eq', $teamIds]
            ], 'id');
            $adminIds = array_unique(array_merge($adminIds, $teamAdminIds));
            $where['admin_id'] = ['in', $adminIds];
        }

        if (!empty($params['id']))
        {
            $where['id'] = ['eq', $params['id']];
        }
        if (!empty($params['name']))
        {
            $where['name'] = ['LIKE', '%'.$params['name'].'%'];
        }
        if (!empty($params['bankNo']))
        {
            $where['bank_no'] = ['LIKE', '%'.$params['bankNo'].'%'];
        }
        if (!empty($params['bankName']))
        {
            $where['bank_name'] = ['LIKE', '%'.$params['bankName'].'%'];
        }
        if (!empty($params['bankTitle']))
        {
            $where['bank_title'] = ['LIKE', '%'.$params['bankTitle'].'%'];
        }
        if (!empty($params['insureEmail']))
        {
            $where['insure_email'] = ['LIKE', '%'.$params['insureEmail'].'%'];
        }
        if (!empty($params['insureEmailSpare']))
        {
            $where['insure_email_spare'] = ['LIKE', '%'.$params['insureEmailSpare'].'%'];
        }
        if (!empty($params['correctionEmail']))
        {
            $where['correction_email'] = ['LIKE', '%'.$params['correctionEmail'].'%'];
        }
        if (!empty($params['correctionEmailSpare']))
        {
            $where['correction_email_spare'] = ['LIKE', '%'.$params['correctionEmailSpare'].'%'];
        }

        $total = CompanyModel::getInstance()->count($where);
        $list = CompanyModel::getInstance()->select($where, '*', $start, $limit);
        return [
            'total' => $total,
            'list' => $list
        ];
    }
}